//
//  UserYJViewController.m
//  练习
//
//  Created by hcios on 2017/7/5.
//  Copyright © 2017年 鹿林. All rights reserved.
//

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

#import "UserYJViewController.h"
#import "YJCollectionViewCell.h"
#import "YJModel.h"
#import "AFNetworking.h"
#import "MJRefresh.h"

@interface UserYJViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    
    NSMutableArray * _dataArray;
    NSInteger page;
}
@property (nonatomic, strong) UICollectionView * cardView;


@end

static NSString     * const CollectionViewCellIdentifier = @"cellID";

@implementation UserYJViewController

#pragma mark - init
- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataArray = [[NSMutableArray alloc] init];
        page = 1;
    }
    return self;
}

#pragma mark - 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化collectionView
    [self layoutCollectionView];
    //自动刷新
    [self.cardView.mj_header beginRefreshing];
    self.view.backgroundColor = [UIColor cyanColor];
    // Do any additional setup after loading the view.
}


#pragma mark - refresh
-(void)refreshGetData:(BOOL)isRefresh{
    
    isRefresh?page = 1:page++;
    NSLog(@"当前页面数量 ：%ld",(long)page);
    NSString * urlString = [NSString  stringWithFormat:@"http://chanyouji.com/api/users/%@.json",_userID];
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:@(page) forKey:@"page"];
    /*网络请求*/
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    [manger GET:urlString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dict = responseObject;
        if (isRefresh) {
            [_dataArray removeAllObjects];
            self.cardView.mj_footer.state = MJRefreshStateIdle;
        }
        if ([dict count]>0) {
            for (NSDictionary * dict in responseObject[@"trips"]) {
                //取值
                YJModel * model = [[YJModel alloc]initWithUserDict:dict];
                if (_dataArray.count == 2) {
                    model.yj_front_cover_photo_url = @"http://p.chanyouji.cn/198148/1421558075861p19btndesdel82so177j1o2d1iqf4.jpg";
                }
                [_dataArray addObject:model];
            }
        }
        if (_dataArray.count < 10) {
            [self.cardView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.cardView reloadData];
        if (!isRefresh && [dict count] == 0) {
            [self.cardView.mj_footer endRefreshingWithNoMoreData];
        }else [self endRefresh];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络请求失败");
    }];
}

-(void)endRefresh{
    
    if (page == 1) {
        [self.cardView.mj_header endRefreshing];
    }else [self.cardView.mj_footer endRefreshing];
}

#pragma mark - 初始化collectionView
- (void)layoutCollectionView{
    
    //初始化layout
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    //滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个cell的大小
    layout.itemSize = CGSizeMake(SCREEN_WIDTH - 20, 210);
    //每个cell之间的距离
    layout.minimumLineSpacing = 10.0f;
    self.cardView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 130) collectionViewLayout:layout];
    self.cardView.delegate = self;
    self.cardView.dataSource = self;
    self.cardView.showsVerticalScrollIndicator = NO;
    //注册cell
    [self.cardView registerClass:[YJCollectionViewCell class] forCellWithReuseIdentifier:@"cellID"];
    self.cardView.backgroundColor = [UIColor colorWithRed:214.0 / 255.0 green:226.0 / 255.0 blue:238.0 / 255.0 alpha:1.0];
    //刷新
    __weak typeof(self) weakSelf = self;
    
    self.cardView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refreshGetData:YES];
    }];
    self.cardView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf refreshGetData:NO];
    }];
    [self.view addSubview:self.cardView];
}


#pragma mark - collectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _dataArray.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YJCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCellIdentifier forIndexPath:indexPath];
    //加载本地数据
    //[cell modelWithDict:_dataArr[indexPath.row]];
    //网络加载
    cell.model = _dataArray[indexPath.row];
    cell.imageViewBtn.hidden = YES;
    return cell;
}

#pragma mark - collectionViewDelegate
//设置边距
- (UIEdgeInsets) collectionView:(UICollectionView *)collectionView
                         layout:(UICollectionViewLayout *)collectionViewLayout
         insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 10.0f);
}

//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld%ld",(long)[indexPath section],(long)[indexPath row]);
}

@end
